package locksynch;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * A bank with a number of bank accounts.
 * @author andy
 */
public class Bank {

    private final double[] accounts;
    private Lock bankLock = new ReentrantLock();

    /**
     * Constructs the bank.
     * @param n the number of accounts.
     * @param initialBalance the initial balance for each account.
     */
    public Bank(int n, double initialBalance) {
        this.accounts = new double[n];
        for (int i = 0; i < this.accounts.length; i++) {
            this.accounts[i] = initialBalance;
        }
    }

    /**
     * Transfers money from one account to another.
     * @param from the account to transfer from
     * @param to the account to transfer to
     * @param amount the amount to transfer
     */
    public void transfer(int from, int to, double amount) {
        this.bankLock.lock();
        try {
            System.out.print(Thread.currentThread());
            this.accounts[from] -= amount;
            System.out.printf(" %10.2f from %d to %d", amount, from, to);
            this.accounts[to] += amount;
            System.out.printf(" Total Balance: %10.2f\n", getTotalBalance());
        } finally {
            this.bankLock.unlock();
        }
    }

    /**
     * Gets the sum of all account balances.
     * @return the total balance
     */
    public double getTotalBalance() {
        double sum = 0;

        for (double account : this.accounts) {
            sum += account;
        }

        return sum;
    }

    /**
     * Gets the number of accounts in the bank.
     * @return the number of accounts.
     */
    public int size() {
        return this.accounts.length;
    }
}
